package com.skydroid.h30

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import com.skydroid.fpvlibrary.serial.SerialPortConnection
import java.io.IOException

/**
 * 与遥控器内部MCU通讯示例
 */
class RCDataActivity: AppCompatActivity() {
    //帧头
    protected val PACKAGE_HEADER_BUF = "fengyingdianzi:".toByteArray()

    protected var mSerialPortConnection: SerialPortConnection? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_rc_data)
        initView()

    }

    companion object{
        fun start(context: Context){
            context.startActivity(
                Intent(context,
                    RCDataActivity::class.java)
            )
        }
    }


    private fun initView(){
        findViewById<View>(R.id.btn_open).setOnClickListener {
            openConnect()
        }
        findViewById<View>(R.id.btn_close).setOnClickListener {
            closeConnect()
        }
        findViewById<View>(R.id.btn_send).setOnClickListener {
            mSerialPortConnection?.sendData("hello".toByteArray())
        }
    }

    /**
     * 打开连接
     */
    private fun openConnect(){
        mSerialPortConnection = SerialPortConnection.newBuilder("/dev/ttyMSM1", 57600)
            .build()

        mSerialPortConnection?.setDelegate(object : SerialPortConnection.Delegate {
            override fun received(bytes: ByteArray, size: Int) {
                //数据回调
                var datas = ByteArray(size)
                System.arraycopy(bytes,0,datas,0,size)
//                    LogUtils.test("received：${String2ByteArrayUtils.bytes2Hex(datas)}")
            }
            override fun connect() {
                //打开成功回调
            }


        })

        try {
            //打开串口
            mSerialPortConnection?.openConnection()
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    /**
     * 关闭连接
     */
    private fun closeConnect(){
        try {
            mSerialPortConnection?.closeConnection()
        } catch (e: IOException) {
            e.printStackTrace()
        }
        mSerialPortConnection = null

    }

    override fun onDestroy() {
        super.onDestroy()
        closeConnect()
    }

}